package com.lovo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration//定义配置类
@ComponentScan(basePackages = "com.lovo")
@EnableAspectJAutoProxy(proxyTargetClass = true)
//Hibernate数据库使用和springData
@EnableJpaRepositories(basePackages = "com.lovo.dao")
@EnableTransactionManagement
public class ApplicationConfig {
    @Bean
    public DataSource dataSource(DBProperties dbProperties) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(dbProperties.getUrl());
        dataSource.setDriverClassName(dbProperties.getDriver());
        dataSource.setUsername(dbProperties.getUser());
        dataSource.setPassword(dbProperties.getPwd());
        return dataSource;
    }

    //配置Hibernate环境
    @Bean
    public HibernateJpaVendorAdapter hibernateJpaVendorAdapter() {
        return new HibernateJpaVendorAdapter();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter hibernateJpaVendorAdapter, DBProperties propertiesConfig) {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setJpaVendorAdapter(hibernateJpaVendorAdapter);
        entityManagerFactoryBean.setPackagesToScan(propertiesConfig.getPackageScan());
        Properties prop = new Properties();
//        数据库语言
        prop.setProperty("hibernate.dialect", propertiesConfig.getDialect());
//        打印时是否展示sql
        prop.setProperty("hibernate.show_sql", propertiesConfig.isShowSql() + "");
//       打印sql是否格式化，空行
        prop.setProperty("hibernate.format_sql", propertiesConfig.isFormatSql() + "");
        entityManagerFactoryBean.setJpaProperties(prop);
        return entityManagerFactoryBean;
    }


    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}
